<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\CaseDelay;
use app\api\model\v1\Collect;
use app\api\model\v1\OperateLog;
use app\api\model\v1\Project;
use app\api\model\v1\ProjectSample;
use app\api\model\v1\ProjectTarget;
use app\api\model\v1\Rectification;
use app\api\model\v1\RectifyAndReformRules;
use app\api\model\v1\Score;
use app\BaseController;
use think\helper\Str;
use think\Request;

class Audit extends BaseController
{


    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/4
     * Time: 21:27
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 整改数据源列表
     */
    public function getZgAuditList(){
        $limit = $this->request->param('limit',10);
        $map = [];
        $map[] = array('type','<>',Rectification::IS_TYPE_THREE); //延期审核
        //退回审核
        $map[] = array('type','<>',Rectification::IS_TYPE_FIVE); //当前的退回是到各级单位管理手中
        $map[] = array('type','<>',Rectification::IS_TYPE_SIX); //此处的退回是指到达最后的管理员手中
        $res = Rectification::with(['admin','unit','project','collect'=>['community','project','target','sample','admin']])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item,$key){
            if ($item['collect']){
                //采集资料
                $item['path_arr'] = json_decode($item['collect']['path'],true);
                //问题描述 社区+项目+指标
                $item['question_desc'] = $item['collect']['community']['community_title'].'--'.$item['collect']['project']['project_title'].'--'.$item['collect']['target']['target_title'];
                //整改状态
                $item['type_name'] = Rectification::$is_type[$item['type']] ?? '';
            }
            if ($item['rec_path']){
                $item['zg_path_arr'] = json_decode($item['rec_path'],true); //整改资料
            }
            $collect_date = date("Y-m-d",strtotime($item['collect']['create_time']));
            $now_date = date("Y-m-d",time());
            $date_diff = diffBetweenTwoDays($now_date,$collect_date);
            $item['diff'] = $date_diff.'-'.$item['time_limit'];
            //审核状态
            $item['status_name'] = Rectification::$is_status[$item['status']] ?? '';
            return $item;
        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/11 9:45
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 延期审核案件
     */
    public function getDelayAuditList(){
        $limit = $this->request->param('limit',10);
        $map = [];
        $map[] = array('type','=',Rectification::IS_TYPE_THREE); //延期审核
        $res = Rectification::with(['admin','unit','project','collect'=>['community','project','target','sample','admin']])->where($map)->order('type asc')->paginate($limit)->each(function ($item,$key){
            if ($item['collect']){
                //采集资料
                $item['path_arr'] = json_decode($item['collect']['path'],true);
                //问题描述 社区+项目+指标
                $item['question_desc'] = $item['collect']['community']['community_title'].'--'.$item['collect']['project']['project_title'].'--'.$item['collect']['target']['target_title'];
                //整改状态
                $item['type_name'] = Rectification::$is_type[$item['type']] ?? '';
            }
            if ($item['rec_path']){
                $item['zg_path_arr'] = json_decode($item['rec_path'],true); //整改资料
            }
            $collect_date = date("Y-m-d",strtotime($item['collect']['create_time']));
            $now_date = date("Y-m-d",time());
            $date_diff = diffBetweenTwoDays($now_date,$collect_date);
            $item['diff'] = $date_diff.'-'.$item['time_limit'];
            //审核状态
            $item['status_name'] = Rectification::$is_status[$item['status']] ?? '';
            return $item;
        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/11 17:24
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 退回案件
     */
    public function getBackAuditList(){
        $limit = $this->request->param('limit',10);
        $map = [];
        $map[] = array('type','=',Rectification::IS_TYPE_SIX); //延期审核
        $res = Rectification::with(['admin','unit','project','collect'=>['community','project','target','sample','admin']])->where($map)->order('type asc')->paginate($limit)->each(function ($item,$key){
            if ($item['collect']){
                //采集资料
                $item['path_arr'] = json_decode($item['collect']['path'],true);
                //问题描述 社区+项目+指标
                $item['question_desc'] = $item['collect']['community']['community_title'].'--'.$item['collect']['project']['project_title'].'--'.$item['collect']['target']['target_title'];
                //整改状态
                $item['type_name'] = Rectification::$is_type[$item['type']] ?? '';
            }
            if ($item['rec_path']){
                $item['zg_path_arr'] = json_decode($item['rec_path'],true); //整改资料
            }
//            $collect_date = date("Y-m-d",strtotime($item['collect']['create_time']));
            //审核状态
            $item['status_name'] = Rectification::$is_status[$item['status']] ?? '';
            return $item;
        });
        return $this->response($res);
    }
    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/4
     * Time: 22:42
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 我的整改
     */
    public function getMyRectification(){
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', 0);
        $map = [];
        if (intval($type) !== Rectification::IS_TYPE_ZERO) {
            if (intval($type) === 4){
                $map[] = ['type', '=', $type + 1];
            }else{
                $map[] = ['type', '=', $type];
            }
        }
        //获取整改管理员和超级管理员
        if(!$this->auth->isSuperAdmin($this->request->wx_id)){
            $group_id_arr = $this->auth->getGroups($this->request->wx_id)->toArray(); //获取当前角色的id
            $new_string = '';
            foreach ($group_id_arr as $k => $v) {
                $new_string .= $v['name'].',';
            }
            $new_string = rtrim($new_string,',');
            if(Str::contains($new_string,'整改管理员')){
                $childrenList = $this->search->getChildrenIds($this->request->wx_unit_id, true);
                $map[] = array('unit_id', 'in', $childrenList);
            }else{
                $map[] = ['admin_id', '=',$this->request->wx_id];
            }
        }
        $res = Rectification::with(['admin','unit','project','collect'=>['community','project','target','sample','admin']])->where($map)->order('id desc')->paginate($limit)->each(function ($item,$key){
            if ($item['collect']){
                //采集资料
                $item['path_arr'] = json_decode($item['collect']['path'],true);
                //问题描述 社区+项目+指标
                $item['question_desc'] = $item['collect']['community']['community_title'].'--'.$item['collect']['project']['project_title'].'--'.$item['collect']['target']['target_title'];
                //整改状态
                $item['type_name'] = Rectification::$is_type[$item['type']] ?? '';
//                //日期
                $item['term_time'] = date("Y-m-d",strtotime($item['collect']['create_time']));
//                $now_date = date("Y-m-d",time());
//                $item['term_diff'] = diffBetweenTwoDays($collect_date,$now_date);
            }
            if ($item['rec_path']){
                $item['zg_path_arr'] = json_decode($item['rec_path'],true); //整改资料
            }

            //审核状态
            $item['status_name'] = Rectification::$is_status[$item['status']] ?? '';
            return $item;
        });;
        return $this->response($res);
    }

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/4
     * Time: 21:01
     * @return \think\response\Json
     * 保存整改审核案件
     */
    public function saveZgAuditCase(){
        $data = $this->request->param();
        $target = ProjectTarget::find($data['target_id']);
        $string_name = '';
        if(!empty($data['admin_ids'])){
            foreach ($data['admin_ids'] as $key=>$v){
                $admin = Admins::find($v);
                if (!is_null($admin)){
                    $string_name .= $admin->username .',';
                    //整改数组
                    $zg_data = [
                        'unit_id'=>$admin->unit_id,
                        'admin_id'=>$v,
                        'project_id'=>$data['project_id'],
                        'collect_id'=>$data['id'],
                        'reform_date'=> time(),  //审核日期
                        'time_limit'=> $target['time_limit'] ?? 0  //整改期限
                    ];
                    Rectification::create($zg_data);
                    //更新采集表状态
                    Collect::update([
                        'id'=>$data['id'],
                        'status'=>Collect::IS_STATUS_TWO //有效案件或者已审核
                    ]);
                    //新增分值
                    Score::create([
                        'admin_id'=>$data['uid'],
                        'collect_id'=>$data['id'],
                        'case_score'=>1,
                        'status'=> Score::IS_STATUS_ONE
                    ]);
                }else{
                    $string_name .= '';
                }
            }
            //操作日志
            AdminLog::record('审核案件', $data['id'], $this->request->uid, $this->request->username);
            //采集日志
            OperateLog::operateRecord($this->request->username.':审核案件,系统推送案件到['.rtrim($string_name,',').']进行整改',$this->request->uid,$this->request->username,$data['id'],OperateLog::IS_COLLECT_TWO);
        }
        return $this->response();
    }

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/4
     * Time: 21:16
     * @return \think\response\Json
     * 案件拒绝
     */
    public function refuseZgAuditCase(){
        $data = $this->request->param();
        //更新采集表状态
        Collect::update([
            'id'=>$data['id'],
            'refuse_desc'=>$data['refuse_desc'],
            'status'=>Collect::IS_STATUS_THREE //无效案件
        ]);
        //操作日志
        AdminLog::record('拒绝案件', $data, $this->request->uid, $this->request->username);
        //采集日志
        OperateLog::operateRecord($this->request->username.':案件审核不通过',$this->request->uid,$this->request->username,$data['id'],OperateLog::IS_COLLECT_TWO);

        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 9:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存整改资料
     */
    public function saveZgCase(){
        $data = $this->request->param();
        foreach ($data['path'] as $key=>$v){
            $data['path'][$key]['thumb'] = $v['url'];
        }
        $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        $data['rec_path'] = $data['path'];
        $data['type'] = Rectification::IS_TYPE_TWO;
        $data['status'] = Rectification::IS_STATUS_ONE;
        $data['content'] = $data['desc'];
        $data['refuse_desc'] = NULL; //设置为空
        $res = Rectification::find($data['zg_id']);
        if (is_null($res)){
            return $this->response(403,'无法找到整改案件');
        }
        $res->save($data);
        //操作日志
        AdminLog::record('上传整改案件', $data, $this->request->wx_id, $this->request->wx_user_name);
        //采集日志
        OperateLog::operateRecord($this->request->wx_user_name.':提交整改案件',$this->request->wx_id,$this->request->wx_user_name,$data['collect_id'],OperateLog::IS_COLLECT_THREE);
        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 10:19
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 查看整改后的详情
     */
    public function checkDetailRec(){
        $zg_id = $this->request->param('zg_id');
        $res = Rectification::with(['admin','unit','project','collect'=>['community','project','target','sample','admin']])->find($zg_id);
        if (is_null($res)){
            return $this->response(403,'无法找到整改案件');
        }
        if ($res['collect']){
            //采集资料
            $res['path_arr'] = json_decode($res['collect']['path'],true);
            //问题描述 社区+项目+指标
            $res['question_desc'] = $res['collect']['community']['community_title'].'--'.$res['collect']['project']['project_title'].'--'.$res['collect']['target']['target_title'];
            //整改状态
            $res['type_name'] = Rectification::$is_type[$res['type']] ?? '';
        }
        if ($res ['rec_path']){
            $res['zg_path_arr'] = json_decode($res['rec_path'],true); //整改资料
        }
        //审核状态
        $res['status_name'] = Rectification::$is_status[$res['status']] ?? '';

        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 10:30
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 审核整改后上传的案件
     */
    public function saveZgAuditCollect(){
        $data = $this->request->param();
        $res = Rectification::find($data['id']);
        if (is_null($res)){
            return $this->response(403,'无法找到整改案件');
        }
        $res->save(['status'=>Rectification::IS_STATUS_TWO]);
        //新增分值
        Score::create([
            'admin_id'=>$data['admin_id'],
            'collect_id'=>$data['collect_id'],
            'case_score'=>0.5,
            'status'=> Score::IS_STATUS_TWO
        ]);
        //操作日志
        AdminLog::record('审核整改案件', $data['id'], $this->request->uid, $this->request->username);
        //采集日志
        OperateLog::operateRecord($this->request->username.':审核整改案件成功',$this->request->uid,$this->request->username,$data['collect_id'],OperateLog::IS_COLLECT_FOUR);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/5 10:31
     * @return \think\response\Json
     * 拒绝整改案件
     */
    public function refuseZgAuditCollect(){
        $data = $this->request->param();
        //更新采集表状态
        Rectification::update([
            'id'=>$data['id'],
            'refuse_desc'=>'整改拒绝:'.$data['refuse_desc'],
            'status'=>Rectification::IS_STATUS_THREE,
            'type'=>Rectification::IS_TYPE_ONE
        ]);
        //操作日志
        AdminLog::record('拒绝整改案件', $data['id'], $this->request->uid, $this->request->username);
        //采集日志
        OperateLog::operateRecord($this->request->username.':拒绝整改案件审核不通过,原因:'.$data['refuse_desc'],$this->request->uid,$this->request->username,$data['collect_id'],OperateLog::IS_COLLECT_FOUR);
        return $this->response();
    }

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/5
     * Time: 23:45
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 处理规则
     */
    public function test(){
        $res = RectifyAndReformRules::where(['single'=>2])->order('id desc')->select()->toArray();

        foreach ($res as $key=>$v){
            $sample = ProjectSample::field('id')->where(['community_id'=>$v['community_id'],'project_id'=>$v['project_id']])->select()->toArray();
            $sample_ids_arr = explode(',',$v['sample_ids']);
            $new_arr = '';
            foreach ($sample_ids_arr as $k1=>$v1){
                foreach ($sample as $k2=>$v2){
                    if($v1 == $v2['id']){
                        $new_arr .= $v1.',';
                    }
                }
            }
            $abc = rtrim($new_arr,',');
            $bbb = RectifyAndReformRules::find($v['id']);
            if ($abc === ""){

                $bbb->delete();
            }else{
                $bbb->save(['sample_ids'=>$abc]);
            }
        }

        halt("数据跑完");
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/11 9:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据整改id 和采集id 获取对应的延期申请数据
     */
    public function delayInfo(){
        $data = $this->request->param();
        $res = CaseDelay::where([
            'rectification_id'=>$data['rectification_id'],
            'collect_id'=>$data['collect_id'],
            'status'=>CaseDelay::IS_STATUS_ONE
        ])->find();
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/11 10:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同意延期案件
     */
    public function agreeDelayCase(){
        $data = $this->request->only(['id','unit_id','admin_id','delay_id','collect_id','time_limit','delay_date']);
        $now_date = date("Y-m-d",time()); //当前时间
        $data['add_time'] = diffBetweenTwoDays($data['delay_date'],$now_date);
        $rectification = Rectification::find($data['id']);
        if (is_null($rectification)){
            return $this->response(403,'无法找到整改案件');
        }
        $delay = CaseDelay::find($data['delay_id']);
        if (is_null($delay)){
            return $this->response(403,'无法找到延期记录');
        }
        //更新整改表
        $rectification->save([
            'time_limit'=>$data['add_time'] + $data['time_limit'],
            'type'=>Rectification::IS_TYPE_ONE
        ]);
        //更新延期申请表
        $delay->save([
            'status'=>CaseDelay::IS_STATUS_TWO //更改当前记录的状态 为已处理
        ]);
        //操作日志
        AdminLog::record('同意延期', $data, $this->request->uid, $this->request->username);
        //采集日志
        OperateLog::operateRecord($this->request->username.':同意延期申请',$this->request->uid,$this->request->username,$data['collect_id'],OperateLog::IS_COLLECT_SEX);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/11 11:17
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 拒绝延期
     */
    public function refuseDelayCase(){
        $data = $this->request->only(['id','unit_id','admin_id','delay_id','collect_id','time_limit','delay_date','refuse_desc']);
        $res = Rectification::find($data['id']);
        if (is_null($res)){
            return $this->response(403,'无法找到整改案件');
        }
        $delay = CaseDelay::find($data['delay_id']);
        if (is_null($delay)){
            return $this->response(403,'无法找到延期记录');
        }
        //更新整改表
        $res->save([
            'refuse_desc'=>'延期拒绝:'.$data['refuse_desc'],
            'type'=>Rectification::IS_TYPE_ONE
        ]);
        //更新延期申请表
        $delay->save([
            'status'=>CaseDelay::IS_STATUS_THREE //更改当前记录的状态 为拒绝
        ]);
        //操作日志
        AdminLog::record('拒绝延期,原因:' . $data['refuse_desc'], $data, $this->request->uid, $this->request->username);
        //采集日志
        OperateLog::operateRecord($this->request->username.':拒绝延期申请,原因:' . $data['refuse_desc'],$this->request->uid,$this->request->username,$data['collect_id'],OperateLog::IS_COLLECT_SEX);
        return $this->response();
    }
}
